/**
 * Copyright (c) 2012-2014 Yunzhisheng(Shanghai) Co.Ltd. All right reserved.
 * @FileName : WindowService.java
 * @ProjectName : DpadnaviVassistProj
 * @PakageName : com.dpadnavi.vassist.background
 * @Author : tomliang
 * @CreateDate : 2015-9-4
 */
package com.dpadnavi.vassist.background;

import java.util.List;
import com.dpadnavi.vassist.R;
import com.dpadnavi.vassist.interfaces.VoiceListener;
import com.dpadnavi.vassist.interfaces.VoiceProtocol;
import com.dpadnavi.vassist.interfaces.imp.BaiduVoiceProtocolImp;
import com.dpadnavi.vassist.manager.ActionManager;
import com.dpadnavi.vassist.model.BaiduVoiceResponeModel;
import com.dpadnavi.vassist.utils.LogUtils;
import com.dpadnavi.vassist.utils.PackageUtil;
import com.dpadnavi.vassist.view.ui.MicrophoneControl;
import com.dpadnavi.vassist.view.ui.ScreenFloatView;
import com.dpadnavi.vassist.view.ui.SessionLinearLayout;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;

/**
 * @Module : 隶属模块名
 * @Comments : 描述
 * @Author : tomliang
 * @CreateDate : 2015-9-4
 * @ModifiedBy : 修改人
 * @ModifiedDate: 2015-9-4
 * @Modified: 2015-9-4: 实现基本功能
 */
public class WindowService extends Service {

	private static final String TAG = "WindowService";
	public static WindowService service;
	
	private ScreenFloatView mScreeFloatView;
	private WindowManager mWindowManager;
	private VoiceProtocol<BaiduVoiceResponeModel> mVoice;
	private WindowManager.LayoutParams mWindowParams = new WindowManager.LayoutParams();
	private Point mWindowSize = new Point();
	private SessionLinearLayout mViewRoot;
	private MicrophoneControl mMicrophoneControl;
	private List<String> mLauncherPackage;
	private boolean mPendingStartMicChecker;
	private Context  mContext;
	
	private Handler mHandler = new Handler();
	
	private VoiceListener<BaiduVoiceResponeModel> listener = new VoiceListener<BaiduVoiceResponeModel>() {

		@Override
		public void onReadyForSpeech() {
			LogUtils.i("TalkService", "onReadyForSpeech");
		}

		@Override
		public void onPartialResults(String[] results) {
			LogUtils.i("TalkService", "onPartialResults");
		}

		@Override
		public void onResults(BaiduVoiceResponeModel data) {
			LogUtils.i("TalkService", "onResults");
			ActionManager.getInstance().checkAction(data);
		}

		@Override
		public void onError(int error) {
			LogUtils.i("TalkService", "onError");
		}

		@Override
		public void onEndOfSpeech() {
			LogUtils.i("TalkService", "onEndOfSpeech");
		}
	};
	
	private Runnable mRunnable = new Runnable() {
		@Override
		public void run() {
			if (mEnableFloatMic) {
				if ((PackageUtil.isHome(WindowService.this, mLauncherPackage) || PackageUtil
						.isRunningForeground(WindowService.this))) {
					showFloatView();
				} else {
					hideFloatView();
				}
				startFloatMicChecker(500);
			} else {
				hideFloatView();
			}
		}
	};

	// 获取服务对象
	public static WindowService getService() {
		return service;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	public Point getWindowSize() {
		return mWindowSize;
	}

	private void resetWindowParamsFlags() {
		mWindowParams.flags &= ~(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
				| WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES
				| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
				| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
				| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
				| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
				| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	private void initWindowParams() {
		mWindowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
		mWindowParams.format = PixelFormat.RGBA_8888;
		resetWindowParamsFlags();
		mWindowParams.flags =
		// WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
		// |
		WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
				| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
		mWindowParams.gravity = Gravity.CENTER;
		// mWindowParams.windowAnimations = R.anim.slide_right_in;
		Resources res = getResources();
		int width = res.getDimensionPixelSize(R.dimen.window_width);
		int height = res.getDimensionPixelSize(R.dimen.window_height);
		mWindowParams.width = width;
		mWindowParams.height = height;

		updateDisplaySize();
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mContext = this;
		service = this;
		
		mVoice = new BaiduVoiceProtocolImp();
		mVoice.setVoiceListener(listener);
		mVoice.init(getApplicationContext());

		mScreeFloatView = new ScreenFloatView(this);
		mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		mViewRoot = (SessionLinearLayout) View.inflate(this,
				R.layout.window_service_main, null);
		findViews();

		initWindowParams();
		mLauncherPackage = PackageUtil.getLauncherPackages(this);
		showFloatView();
		registerListener();

		mPendingStartMicChecker = true;

	}

	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	private void updateDisplaySize() {
		Display display = mWindowManager.getDefaultDisplay();
		if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
			mWindowSize.y = display.getHeight();
			mWindowSize.x = display.getWidth();
		} else {
			display.getSize(mWindowSize);
		}
		LogUtils.i(TAG, "updateDisplaySize:x " + mWindowSize.x + ",y "
				+ mWindowSize.y);
	}

	private void startFloatMicChecker(long delay) {
		// LogUtil.d(TAG, "startFloatMicChecker: delay " + delay);
		mHandler.postDelayed(mRunnable, delay);
	}

	private void stopFloatMicChecker() {
		LogUtils.i(TAG, "stopFloatMicChecker");
		setFloatMicEnable(false);
		mHandler.removeCallbacks(mRunnable);
	}

	private void findViews() {
		mMicrophoneControl = (MicrophoneControl) mViewRoot
				.findViewById(R.id.microphoneControl);
	}

	private void registerListener() {
		mScreeFloatView.setOnClickListener(mOnClickListener);
	}

	private void unregisterListener() {
		mScreeFloatView.setOnClickListener(null);
	}

	public void showFloatView() {
		if (!mScreeFloatView.isShown()) {
			mScreeFloatView.show();
		}
	}

	public void hideFloatView() {
		if (mScreeFloatView.isShown()) {
			mScreeFloatView.hide();
		}
	}

	private OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View view) {
			if (view == mScreeFloatView.getFloatMicInstance()) {
				LogUtils.i(TAG, "onClick");
//				mMicrophoneControl.setVisibility(View.VISIBLE);
//				show();
				mVoice.start();
			} else if (view.getId() == R.id.bottomCancelBtn) {
				LogUtils.i(TAG, "cancel button onClick");
				// mSessionManager.cancelSession();

				// Message msg = new Message();
				// msg.what = SessionPreference.MESSAGE_UI_OPERATE_PROTOCAL;
				// msg.obj = protocal;
				// mSessionManagerHandler.sendMessage(msg);
			}
		}
	};
	private boolean mEnableFloatMic;

	public void show() {
		if (mViewRoot.isShown()) {
			return;
		}
		LogUtils.i(TAG, "show");
		stopFloatMicChecker();
		hideFloatView();
		mPendingStartMicChecker = true;
		show(mViewRoot);
	}

	public void dismiss() {
		if (!mViewRoot.isShown()) {
			return;
		}
		LogUtils.i(TAG, "dismiss");
		mWindowManager.removeViewImmediate(mViewRoot);
		if (mPendingStartMicChecker) {
			mPendingStartMicChecker = false;
			updateEnableFloatMic();
			startFloatMicChecker(0);
		}
	}

	public void dimissView(View view) {
		if (!view.isShown()) {
			return;
		}
		LogUtils.i(TAG, "prepare view dismiss");
		mWindowManager.removeViewImmediate(view);
		if (mPendingStartMicChecker) {
			mPendingStartMicChecker = false;
			updateEnableFloatMic();
			startFloatMicChecker(0);
		}
	}

	private void updateEnableFloatMic() {
		LogUtils.i(TAG, "updateEnableFloatMic");
		setFloatMicEnable(true);
	}

	private void setFloatMicEnable(boolean enable) {
		LogUtils.i(TAG, "setFloatMicEnable: enable " + enable);
		mEnableFloatMic = enable;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		dismiss();
		unregisterListener();
		stopFloatMicChecker();
		mOnClickListener = null;
		mWindowParams = null;
		mWindowSize = null;
		mLauncherPackage.clear();
		mLauncherPackage = null;
	}

	private void show(View view) {
		if (view == null || view.isShown()) {
			return;
		}
		// 弹出框强制横屏
		if (mWindowParams.screenOrientation != ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
			mWindowParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
		}

		mWindowManager.addView(view, mWindowParams);
	}
}
